import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react';
import cls from 'classnames';
import { Button, Pagination, PaginationProps } from 'antd';
import { RightOutlined, SyncOutlined } from '@ant-design/icons';
import { getMessage } from '@inbiz/react';
import './index.less';

interface BasePaginationProps {
  onPageChange?: (pageInfo: { current: number; pageSize: number }) => void;
  refreshData?: () => void;
  pagination?: PaginationProps;
  pageRefresh?: boolean;
}

const BasePagination = (props: BasePaginationProps) => {
  const { pagination = {}, onPageChange, refreshData, pageRefresh = false } = props;
  const [nextBtn, setNextBtn] = useState<boolean>(true);
  const paginationRef = useRef<any>(null);
  const paginationPrefixCls = 'inbiz-pagination';
  const config = useMemo(() => {
    return {
      itemRender: (page: number, type: 'page' | 'prev' | 'next' | 'jump-prev' | 'jump-next', originalElement: React.ReactNode) => {
        if (type === 'next') {
          return (
            <>
              <Button
                disabled={nextBtn}
                className='ant-pagination-item-link inbiz-pagination-next-btn'
                icon={<RightOutlined />}
              />
              {pageRefresh && (
                <span className='inbiz-pagination-refresh'>
                  <Button
                    className='inbiz-pagination-refresh-btn'
                    icon={<SyncOutlined />}
                    onClick={(e) => {
                      e && e.stopPropagation();
                      refreshData && refreshData();
                    }}
                  />
                </span>
              )}
            </>
          );
        }
        return originalElement;
      },
      ...pagination,
      showTotal: (total: number) => {
        if (!total) return null;
        // 另加了一个类型，兼容之前
        if (pagination?.showTotal === true) {
          return `${getMessage('Pagination.total')} ${total} ${getMessage('Pagination.items')}`
        }
        return pagination.showTotal ? pagination.showTotal(total) : null
      },
    };
  }, [pagination, nextBtn]);

  const onChange = useCallback((page: number, pageSize: number) => {
    onPageChange && onPageChange({ current: page, pageSize });
  }, [onPageChange]);

  useEffect(() => {
    const pagin = paginationRef.current.querySelector('.ant-pagination-next');
    pagin?.removeAttribute('title');
    const isDisabled = pagin?.getAttribute('aria-disabled');
    setNextBtn(isDisabled ? JSON.parse(isDisabled) : false);
  });

  return (
    <div className={cls([paginationPrefixCls, pageRefresh ? 'inbiz_page_refresh' : ''])} style={{ zIndex: 2 }} ref={paginationRef}>
      <Pagination {...config} onChange={onChange} />
    </div>
  );
};

export default React.memo(BasePagination);
